import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useLocation, useNavigate } from 'react-router-dom';
// import { ProcessedNotification } from 'src/model/Notification';
import { reduceNotification } from 'src/redux/uiSlice';
import { updatePushMsg } from 'src/service/sysConfigService'
import Toast from '../Toast';
import { Page } from 'src/constant/Page';

type ProcessedNotification = any

type Props = {
    content: ProcessedNotification[];
};

const ToastGroup = ({ content }: Props) => {
    const { pathname } = useLocation();
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const [top, setTop] = useState<number[]>([]);
    const itemsRef = useRef<(HTMLDivElement | null)[]>([]);
    const token = localStorage.getItem("token")
    useEffect(() => {
        const tmp = content.map((o, i) =>
            itemsRef.current
                .slice(0, i)
                .map((v) => v?.clientHeight ?? 0)
                .reduce((sum, current) => sum + current + 15, 15),
        );
        setTop(tmp);
    }, [content]);

    const onClose = (i: number, id: string) => {
        dispatch(reduceNotification(i));
        updatePushMsg({
            FID: id,
            token: token
        })
    };

    const onGoNav = (i: number, id: string, type: number) => {
        if (type == 1) {
            navigate(Page.OrderAll)
        } else if (type == 2) {
            navigate(Page.Record)
        } else if (type == 3) {
            navigate(Page.Record + "?type=withdrawal")
        }
    }

    return (
        <div>
            {content.map((v, i) => (
                <Toast
                    key={v.FID}
                    myRef={(el) => (itemsRef.current[i] = el)}
                    onClose={() => onClose(i, v.FID)}
                    top={top[i] === undefined ? 0 : top[i]}
                    message={v.FNote}
                    // onNavigate={v.to.startsWith(pathname) ? () => navigate(0) : () => navigate(v.to)}
                    onNavigate={() => { onGoNav(i, v.FID, v.FType) }}
                />
            ))}
        </div>
    );
};

export default ToastGroup;
